#!/usr/bin/ruby

MAX=50

a=ARGV.collect { |x| Integer(x) }
a=Array.new(MAX,MAX).collect { |x| Integer( rand() * x ) } if a.length() == 0

def print_array( a )
  system "clear"
  MAX.downto(1) {
    |line|
    for v in a do
      print v>=line ? '|' : ' '
    end
    print "\n"
  }
end

def compare( a, b )
  return a < b
end

def merge( a, b )
  c=Array.new()
  while a.length() > 0 and b.length() > 0 do
    if compare( a[0], b[0] ) then
      c.push( a.shift() ) 
    else
      c.push( b.shift() ) 
    end
  end
  (c.concat(a)).concat(b)
  return c
end

def mergesort( a )
  return a if a.length() <= 1
  n = a.size()/2
  return merge(mergesort(a[0,n]),
	       mergesort(a[n..-1]))
end

print_array( a )
a=mergesort( a )
sleep 1
print_array( a )
